﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Web.Models;
using System.Web.Security;
using Web.Helper;
using RentalSystem.Data.EF;
using Web.Context;

namespace Web.Controllers
{
    public class AccountController : BaseController
    {
        [HttpGet]
        public ActionResult Login()
        {
            if (IsUserAuthenticated)
                ViewBag.AuthenticatedUserName = CurrentUser.DisplayName;

            return View();
        }

        [HttpPost]
        public ActionResult Login(LoginData model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    if (string.IsNullOrEmpty(model.Password) || string.IsNullOrEmpty(model.UserEmail))
                    {
                        ModelState.AddModelError("", "Uzupełnij pola!");
                    }

                    if (Membership.ValidateUser(model.UserEmail, Crypto.ComputeMD5(model.Password)))
                    {
                        Users user = DataContext.UsersDao.ValidateUser(model.UserEmail, Crypto.ComputeMD5(model.Password));
                        SecurityManager.LoginUser(user);
                        LogManager.UserLogin(user.UserGuid);

                        if(CurrentUser.RoleId == 1)
                            return RedirectToAction("Index", "Customers");

                        return RedirectToAction("Index", "Workers");
                    }

                    ModelState.AddModelError("", "Niepoprawny login lub hasło!");
                    return View(model);
                }
                catch (Exception exc)
                {
                    ModelState.AddModelError("", exc.Message);
                    return View(model);
                }
            }

            ModelState.AddModelError("", "Błąd walidacji!");
            return View(model);
        }

        [HttpGet]
        public ActionResult Logout()
        {
            if(CurrentUser != null)
                LogManager.UserLogout(CurrentUser.Guid);
            CurrentContext.Context.CurrentUser = null;
            FormsAuthentication.SignOut();
            Session.Clear();
            Session.Abandon();

            return RedirectToAction("Start", "Public");
        }

        [HttpGet]
        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegistryData model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    model.Customer = new Customers();
                    model.Customer.Persons = model.Person;
                    model.User.Customers = model.Customer;

                    string error = EntityManager.ValidateNewUser(model.User);
                    if (!String.IsNullOrEmpty(error))
                    {
                        ModelState.AddModelError("",error);
                        return View(model);
                    }
                    if (model.Person.PersonBirthDate.Ticks > DateTime.Now.AddYears(-18).Ticks)
                    {
                        ModelState.AddModelError("", "Założyć konto mogą jedynie osoby pełnoletnie");
                        return View(model);
                    }
                    
                    Users newUser = EntityManager.FillDefaultUserData(model.User, model.Password, UserRolesTypes.Customer);

                    this.DataContext.UsersDao.Add(newUser);
                    LogManager.UserRegistered(newUser.UserGuid);
                    EntityManager.UpdateStatsNewUser();
                    ViewBag.ActionResult = "Użytkownik został zarejestrowany!";
                    return View();
                }
                catch (Exception exc)
                {
                    ModelState.AddModelError("", exc.Message);
                    return View(model);
                }
            }

            //ModelState.AddModelError("", "Błąd walidacji!");
            return View(model);
        }
    }
}
